<template>
    <div class="login">
        <van-form class="form" @submit="OnLogin">
                <div class="avatar">
                    <img src="/assets/images/avatar.png" />
                </div>

                <van-field 
                    v-model="business.mobile"
                    name="mobile"
                    placeholder="手机号码"
                    left-icon="phone-o"
                    :rules="[
                        {required: true, message: '请填写手机号码'},
                        {pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确'}
                    ]"
                />

                <van-field 
                    v-model="business.password"
                    type="password"
                    name="password"
                    placeholder="密码"
                    left-icon="warn-o"
                    :rules="[{required: true, message: '请填写密码'}]"
                />

                <div class="button">
                    <van-button round block color="linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)" native-type="submit">注册 登录</van-button>
                </div>
                    
                <div class="forget">
                    <router-link to="/">返回首页</router-link>
                </div>
        </van-form>
    </div>
</template>

<script setup>
import { onBeforeMount, ref } from 'vue';
//获取全局上下文
const { proxy } = getCurrentInstance();
//登录表单数据
const business = reactive({
    mobile:13800000000, //默认手机号
    password:123    //默认密码
});

//接收地址栏的token值
const token = ref('');

//页面加载前执行
onBeforeMount(() => {
    //从URL获取token并存储到cookie中
    token.value = proxy.$route.query.token ?? '';

    if(token.value)
    {
        proxy.$cookies.set('token',token.value);
    }


    if (Object.getOwnPropertyNames(proxy.$business.value).length > 0) {
        proxy.$success('您已成功登录,无需重复登录',() => proxy.$router.push('/business'));
    }
})

const OnLogin = async () =>
{

    token.value = token.value ? token.value : proxy.$cookies.get('token');

    if(token.value)
    {
        business.token = token.value;
    }

    const result = await proxy.$http.post('/business/login',business);

    if(result.code === 1)
    {
        proxy.$success(result.msg,() =>
        {
            proxy.$business.value = result.data;

            const action = proxy.$cookies.get('action');

            if(action === 'login')
            {
                // 清除cookie
                proxy.$cookies.remove('action');

                proxy.$router.back();
            }else{
                proxy.$router.push(result.url);
            }
        });
    }else{
        proxy.$fail(result.msg);
    }
}
</script>

<style scoped>
@import url('/assets/css/login.css');
</style>